<?php
/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author yuan1994 <tianpian0805@gmail.com>
 * @link http://tpadmin.yuan1994.com/
 *
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

//------------------------
// 用户控制器
//-------------------------

namespace app\admin\controller\qzuser;

use app\common\controller\Backend;
use think\Db;

//use think\Db\Where;
//use think\Exception;

class Qzuser extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
    }

    //用户信息列表
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //$map = new Where;
            $map['isdelete'] = ["eq", 0];
            //获取当前年,转为int
            $year = intval(date('Y'));
            //dump($year);
            //昵称查询
            if ($this->request->param('nickname')) {
                $map['nickname'] = ['nickname', "like", "%" . $this->request->param('nickname') . "%"];
            }
            //账号查询
            if ($this->request->param('userid')) {
                $map['userid'] = ['userid', "like", "%" . $this->request->param('userid') . "%"];
            }
            //手机号查询
            if ($this->request->param('phone')) {
                $map['phone'] = ['phone', "like", "%" . $this->request->param('phone') . "%"];
            }
            //性别查询
            if ($this->request->param('sex')) {
                $map['sex'] = ['eq', $this->request->param('sex')];
            }
            //身高查询
            if ($this->request->param('height')) {
                $height = explode('-', $this->request->param('height'));
                $map['height'] = ['between', [$height[0], $height[1]]];
            }
            //体重查询
            if ($this->request->param('weight')) {
                $weight = explode('-', $this->request->param('weight'));
                $map['weight'] = ['between', [$weight[0], $weight[1]]];
            }
            //区域查询
            if ($this->request->param('province')) {
                $map['province'] = ['eq', $this->request->param('province')];
            }
            //年龄查询
            if ($this->request->param('age')) {
                $age = explode('-', $this->request->param('age'));
                //dump($age);//ok
                //获取需要时间区间的时间戳
                $age['0'] = strtotime('-' . $age['0'] . " year");
                $age['1'] = strtotime('-' . $age['1'] . " year");
                $map['birthday'] = ['between', [$age['1'], $age['0']]];
            }
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
//            if($this->request->param('sort')=="age"){
//                $sort="birthday";
//            }
            list($map, $sort, $order, $offset, $limit) = $this->buildparams();
            //各种用户总数查询
//            $use['count'] = Db::name('qz_user')->where($map)->count();
//            $use['ptuse'] = Db::name('qz_user')->where($map)->where('use_type', 1)->count();
//            $use['druse'] = Db::name('qz_user')->where($map)->where('use_type', 2)->count();
//            $use['sjuse'] = Db::name('qz_user')->where($map)->where('use_type', 3)->count();

            $count = Db::name('qz_user')->where($map)->count();
            //$this->view->assign('use', $use);
            $list = Db::name('qz_user')->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //获取js需要的数据
            foreach ($list as $k => $v) {
                $list[$k]['age'] = $year - (date('Y', $list[$k]['birthday']));
                $list[$k]['tige'] = $list[$k]['height'] . "/" . $list[$k]['weight'];
                $list[$k]['diqu'] = $list[$k]['province'] . "-" . $list[$k]['city'] . "-" . $list[$k]['area'];
            }

            //$this->view->assign('list',$list);
            //dump($list);die;
            $result = array("total" => $count, "rows" => $list);
            //echo 2222;exit;
            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 修改密码
     */
//    public function password()
//    {
//        $id = $this->request->param('id/d');
//        if ($this->request->isPost()) {
//            //禁止修改管理员的密码，管理员id为1
//            if ($id < 2) {
//                return ajax_return_adv_error("缺少必要参数");
//            }
//
//            $password = $this->request->post('password');
//            if (!$password) {
//                return ajax_return_adv_error("密码不能为空");
//            }
//            if (false === \think\facade\App::model('AdminUser')->updatePassword($id, $password)) {
//                return ajax_return_adv_error("密码修改失败");
//            }
//            return ajax_return_adv("密码已修改为{$password}", '');
//        } else {
//            // 禁止修改管理员的密码，管理员 id 为 1
//            if ($id < 2) {
//                throw new Exception("缺少必要参数");
//            }
//
//            return $this->view->fetch();
//        }
//    }

    //加密的id生成
    public function idjiami()
    {
        //根据id倒序查询数据库，取第一条数据得到数据库最后一条数据，+1得到添加后新的id，进行加密
        $user = Db::name('qz_user')->where('isdelete', 0)
            ->order('id', 'desc')
            ->limit(1)
            ->value('id');
        //dump($user);die;
        //没有用户数据时，newid=1;
        if (is_null($user)) {
            $newid = 1;
        }
        $newid = $user + 1;
        //echo $newid;die;
        //此方法必须16位不同字符加密，so淘汰
        //$alphabetint = '1234567890';
        //$hashids = hashids(8,"tpadmin","1234567890123456789");
        //$encode_id = $hashids->encode($newid); //加密
        $encode_id = alphaID($newid, false, 8);
        return $encode_id;
        //dump($user);die;
    }

    //添加用户

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $data['userid'] = trim($param['userid']);
            //判断userid是否存在（id唯一性）
            $is_cz = Db::name('qz_user')->where('userid', $data['userid'])
                ->value('userid');
            if ($is_cz) {
                $this->error(__('id已存在'));
            } else {
                $data['nickname'] = trim($param['nickname']);
                if (trim($param['password']) == "") {
                    $data['password'] = md5(123456);
                }
                $data['password'] = md5(trim($param['password']));
                $data['use_type'] = trim($param['use_type']);
                $data['prased'] = trim($param['prased']);
                $data['card_num'] = trim($param['card_num']);
                $data['birthday'] = time($param['birthday']);
                $data['creat_time'] = time($param['creat_time']);
                $data['phone'] = trim($param['phone']);
                //dump($data);die;
                $save = Db::name('qz_user')->insert($data);
                if ($save) {
                    $this->success('ok');
                }
            }
        } else {
            $id = $this->idjiami();
            $this->assign('id', $id);
            return $this->view->fetch();
        }
    }

    //修改用户信息
    public function edit($ids = NULL)
    {
        if ($this->request->isPost()) {
            if (!is_null($ids)) {
                $param = $this->request->param();
                //如果传参是有row['prased']则是修改获赞量，如果是row['card_num']则是体验卡数量
                if (!empty($param['row']) && isset($param['row']['prased'])) {
                    $res = Db::name('qz_user')->where('userid', $param['ids'])->update(['prased' => $param['row']['prased']]);
                    if ($res) {
                        $this->success("ok");
                    } else {
                        $this->error(__('失败'));
                    }
                } elseif (!empty($param['row']) && isset($param['row']['card_num'])) {
                    $res = Db::name('qz_user')->where('userid', $param['ids'])->update(['card_num' => $param['row']['card_num']]);
                    if ($res) {
                        $this->success("ok");
                    } else {
                        $this->error(__('失败'));
                    }
                } else {
                    $data['nickname'] = trim($param['nickname']);
                    $data['sex'] = trim($param['sex']);
                    $data['birthday'] = time($param['birthday']);
                    $data['school'] = trim($param['school']);
                    $data['height'] = trim($param['height']);
                    $data['weight'] = trim($param['weight']);
                    $data['phone'] = trim($param['phone']);
                    $data['use_type'] = trim($param['use_type']);
                    $data['is_binding'] = trim($param['is_binding']);
                    //绑定手机号不为空的话，修改绑定状态为已绑定
                    if (!is_null($data['bind_phone'])) {
                        $data['is_binding'] = "1";
                    } else {
                        $data['is_binding'] = "0";
                    }
                    $data['bind_phone'] = trim($param['bind_phone']);
                    $data['phone'] = trim($param['phone']);
                    $data['prased'] = trim($param['prased']);
                    $data['card_num'] = trim($param['card_num']);
                    $data['introduct'] = trim($param['introduct']);
                    if ($data) {
                        $res = Db::name('qz_user')->where('userid', $ids)->save($data);
                    }
                }
            }
        } else {
            $row = Db::name('qz_user')->where('userid', $ids)
                ->find();
            $this->assign('row', $row);
            return $this->view->fetch();
        }
    }


    /**
     * 查看用户详情
     */
    public function detail($ids = NULL)
    {
        if(!is_null($ids)) {
            $row = Db::name('qz_user')->where('userid', $ids)->find();
            if (!$row)
                $this->error(__('失败'));
            if ($this->request->isAjax()) {
                $this->success("ok", null, ['id' => $ids]);
            }
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
    }

    /**
     * 修改用户状态，禁用与启用
     * @param int $ids 用户的userid
     * @param int $params 用户的状态
     * 为1，是已经启用了，传过来就需要做禁用操作，存入数据库值为0
     * 为1，是被禁用了，传过来就需要做启用操作，存入数据库值为1
     */

    public function updatestatus($ids = NULL)
    {
        $status = $this->request->param('params');
        if (!is_null($ids) && $status == "1") {
            $status = "0";
            $res = Db::name('qz_user')->where('userid', $ids)->update(['status' => $status]);
            if ($res) {
                $this->success('禁用成功');
            } else {
                $this->success('禁用失败');
            }
        } else if (!is_null($ids) && $status == "0") {
            $status = "1";
            $res = Db::name('qz_user')->where('userid', $ids)->update(['status' => $status]);
            if ($res) {
                $this->success('启用成功');
            } else {
                $this->success('启用失败');
            }
        }
    }

}